package nbcp.mvc

import nbcp.base.db.KeyValueString
import nbcp.base.event.RequestInitEvent
import nbcp.base.model.HttpFeignLogData
import nbcp.base.model.HttpRequestModel
import nbcp.base.utils.SpringUtil
import nbcp.mvc.sys.*
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

object HttpContext {

    private  var _lastRequest = ThreadLocal.withInitial<HttpRequestModel?> { null }
    private  var _lastRequestType = ThreadLocal.withInitial<Class<*>?> { null }

    var lastRequest: HttpRequestModel?
        get(){
            return _lastRequest.get();
        }
        set(v){
            _lastRequest.set(v);
        }

    var lastRequestType: Class<*>?
        get(){
            return _lastRequestType.get();
        }
        set(v){
            _lastRequestType.set(v);
        }


    val clientIp: String
        get() = request.ClientIp

    val xTraceId: String
        get() = request.XTraceId

    val tokenValue: String get() = request.tokenValue

    val token: KeyValueString get() = request.token


    private var _request = ThreadLocal.withInitial<HttpServletRequest?> { null }
    private var _response = ThreadLocal.withInitial<HttpServletResponse?> { null }

    @JvmStatic
    fun init(request: HttpServletRequest, response: HttpServletResponse): Boolean {
        _request.set(request);
        _response.set(response);
        return true
    }

    @JvmStatic
    val hasRequest: Boolean
        get() {
            if (_request.get() != null) return true;
            if ((RequestContextHolder.getRequestAttributes() as ServletRequestAttributes?)?.request != null) {
                return true;
            }
            return false;
        }


//    @JvmStatic
//    val hasResponse: Boolean
//        get() {
//            if (_response.get() != null) return true;
//            if ((RequestContextHolder.getRequestAttributes() as ServletRequestAttributes?)?.response != null) {
//                return true;
//            }
//            return false;
//        }

    @JvmStatic
    val request: HttpServletRequest
        get() {
            return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes?)?.request
                ?: _request.get()
                ?: throw RuntimeException("找不到 HttpServletRequest")
        }

    @JvmStatic
    val response: HttpServletResponse
        get() {
            return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes?)?.response
                ?: _response.get()
                ?: throw RuntimeException("找不到 HttpServletResponse")
        }
}